package com.kdd.campus.pay.controller;

import cn.hutool.json.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.kdd.campus.common.entity.CommonResult;
import com.kdd.campus.pay.service.PayService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @Auther: fcp
 * @Date: 2020/5/18 10:32
 * @Description:
 */
@RestController
@RequestMapping("pay")
public class PayController {
    @Autowired
    private PayService payService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment environment;

    @GetMapping("paymentCode")
    public CommonResult generatePaymentCode(String totalFee,String outTradeNo) throws Exception {
        String paymentCode = payService.generatePaymentCode(totalFee , outTradeNo);
        return CommonResult.success(paymentCode);
    }

    @GetMapping
    public String test(){
        return "内网穿透成功";
    }

    /**
     *  后台通知交互时，如果微信收到商户的应答不符合规范或超时，微信会判定本次通知失败，重新发
     *  送通知，直到成功为止（在通知一直不成功的情况下，微信总共会发起10次通知，通知频率为
     *  15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - 总计 24h4m），但微信不保证通知最终一定能成功。
    */
    // 微信支付成功的回调方法
    @PostMapping("notify")
    public String notifyUrl(HttpServletRequest request) throws Exception {

        // 微信回调数据是二进制流，我们需要提取二进制流转换为字符串，这个字符串是xml格式
        String xmlString = ConvertToString(request);
        Map<String, String> map = WXPayUtil.xmlToMap(xmlString);
        // 判断该通知是否为重复通知

        // 做签名验证，并验证实付订单金额是否与数据库中订单金额一致
        rabbitTemplate.convertAndSend(environment.getProperty("mq.pay.order.exchange"), environment.getProperty("mq.pay.order.routingKey"), map);

        // 微信返回一个成功的响应
        return "<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

    // 输入流转换成XML字符串
    private String ConvertToString(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = -1;
        byte[] buffer = new byte[1024];
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        String result = new String(outputStream.toByteArray(), "utf-8");
        return result;
    }


}
